package com.example.demo.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;

import static com.sun.xml.internal.rngom.parse.compact.CompactSyntaxConstants.WS;


/**
 * cgLib是一个强大的高性能的代码生成包，提供方法的拦截。
 * Hibernate使用cglib来代理单端关联，EasyMock和jMock通过使用模仿对象来测试Java代码。
 * cgLib包的底层是使用一个小而快的字节码处理框架ASM，来转换字节码并生成新的类。
 * Created by alva on 18/6/27.
 */
public class EchancerDemo {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(EchancerDemo.class);
        enhancer.setCallback(new MethonInterceptionImpl());
        EchancerDemo demo = (EchancerDemo) enhancer.create();
        demo.test();
//        System.out.println(demo);
        Optional<String> aa = Optional.of("alva");
        System.out.printf(aa.get());
        OptionalDouble doubleValue = OptionalDouble.of(233);
        System.out.println(doubleValue);
    }

    public void test(){
        System.out.println("EchancerDemo test()");
    }

    private static class MethonInterceptionImpl implements MethodInterceptor {
        @Override
        public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            System.out.println("before invoke " + method);
            Object result = methodProxy.invokeSuper(object,args);
            System.out.printf("after invoke " + method);
            return result;
        }
    }
    //并行编程
    private static String getFirstResult(String question, List<String> engines) {
        // get element as soon as it is available
        Optional<String> result = engines.stream().parallel().map((base) -> {
            String url = base + question;
            return url;
        }).findAny();
        return result.get();
    }
}